package com.anttribe.components.db.executor;

import javax.sql.DataSource;

import com.anttribe.components.db.executor.config.SqlExecutorConfiguration;
import com.anttribe.components.db.executor.exception.SqlExecutorExcetion;
import com.anttribe.components.db.metadata.datasource.DataSourceProxy;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhaoyong
 * @date 2023/1/4 0004
 */
@Slf4j
public class SqlExecutorFactory {
    /**
     * DatabaseSupplierFactory
     *
     * @return DatabaseSupplierFactory
     */
    public static SqlExecutorFactory me() {
        return SqlExecutorFactory.SqlExecutorFactoryInstance.INSTANCE;
    }

    /**
     * 获取SqlExecutor执行器
     *
     * @param dataSource
     *            DataSource
     * @return SqlExecutor
     */
    public SqlExecutor getSqlExecutor(DataSource dataSource) {
        return getSqlExecutor(dataSource, SqlExecutorConfiguration.builder().build());
    }

    /**
     * 获取SqlExecutor执行器
     * 
     * @param dataSource
     *            DataSource
     * @param sqlExecutorConfiguration
     *            SqlExecutorConfiguration
     * @return SqlExecutor
     */
    public SqlExecutor getSqlExecutor(DataSource dataSource, SqlExecutorConfiguration sqlExecutorConfiguration) {
        if (null == dataSource) {
            throw new SqlExecutorExcetion("Provided NON dataSource for executing sql.");
        }

        if (null == sqlExecutorConfiguration) {
            log.warn("Provided NON sqlExecutorConfiguration, then use the default configuration");
            sqlExecutorConfiguration = SqlExecutorConfiguration.builder().build();
        }

        // 构造DataSourceProxy
        DataSourceProxy dataSourceProxy = new DataSourceProxy(dataSource);
        return new GeneralSqlExecutor(dataSourceProxy, sqlExecutorConfiguration);
    }

    /**
     * 静态内部类实现单例
     */
    private static class SqlExecutorFactoryInstance {

        public static final SqlExecutorFactory INSTANCE = new SqlExecutorFactory();

    }

}